import 'dart:io';

import 'package:common_utils/common_utils.dart';
import 'package:path_provider/path_provider.dart';

///
/// 本地文件缓存管理，依赖path_provider
///
class LocalFileUtils {
  //储存在本地的搜索历史数据
  static String searchHistory = 'search_history.txt';

  //创建一个文件路径
  static createDir(String filePath) async {
    Directory directory = await getApplicationDocumentsDirectory();
    String path = '${directory.path}${Platform.pathSeparator}$filePath';
    // LogUtil.v(path, tag: '当前操作的文件路径=');
    var file = File(path);
    var exist = file.existsSync();
    // LogUtil.v(exist, tag: '当前文件目录是否存在=');
    if (exist) {
      //存在,删除
      file.delete();
    }
    var result = await file.create(recursive: true);
    return result.path;
  }

  static writeContent(String filePath, String jsonStr) async {
    if (jsonStr.isEmpty) {
      // LogUtil.v('写入数据为空，不写入');
      return;
    }
    String path = await createDir(filePath);
    // LogUtil.v(path, tag: '重新创建后=');
    var file = File(path);
    file.writeAsStringSync(jsonStr);
  }

  static readContent(String filePath) async {
    Directory directory = await getApplicationDocumentsDirectory();
    String path = '${directory.path}${Platform.pathSeparator}$filePath';

    var file = File(path);
    if (file.existsSync()) {
      String content = file.readAsStringSync();
      LogUtil.v(content, tag: '读取到的数据=');
      return content;
    } else {
      LogUtil.v(path, tag: '路径不存在=');
      return '';
    }
  }
}
